﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using UIShare;
using EFong.View.Proxy;
using EFong.View.Customer;
using EFong.View.Base;

namespace EFong.View.OtherBusiness
{
    public partial class Frm_OtherBusiness : BasicMdiChildForm
    {
        private Proxy.BusinessServiceProxy _businessProxy {get{ return Proxy.BusinessServiceProxy.GetInstance();}}
        private Proxy.MasterServiceProxy _masterProxy {get{ return Proxy.MasterServiceProxy.GetInstance();}}

        public Frm_OtherBusiness()
        {
            InitializeComponent();
            spe_VendorDiscountOrBasePrice.SetValue(null);
            spe_PrintTotalPrice.SetValue(null);
            spe_Intergral.SetValue(null);
            spe_TotalVendorPrice.SetValue(null);
            spe_TotalPrice.SetValue(null);
            spe_Price.SetValue(null);
            spe_TotalProfit.SetValue(null);
            spe_Qty.SetValue(null);

            rad_SCustomer.SetValue(false);
            rad_SOrderDate.SetValue(false);
            rad_SOrderRef.SetValue(false);
            rad_SProject.SetValue(false);
            rad_SVendor.SetValue(false);

            this.bbt_Void.Visibility = AppParameters.IsAdRole ? DevExpress.XtraBars.BarItemVisibility.Always : DevExpress.XtraBars.BarItemVisibility.Never;
        }

        protected override void InitFields()
        {
        }

        protected override void Events()
        {
            this.gv_Orders.FocusedRowChanged += (s, e) =>
                {
                    Contract.ROtherBusiness otherBusiness = this.gv_Orders.GetRow(e.FocusedRowHandle) as Contract.ROtherBusiness;

                    if (otherBusiness != null)
                    {
                        Order = _businessProxy.GetOtherBusinessByID(otherBusiness.ID).ReturnValue;
                    }
                    else
                    {
                        Order = null;
                    }
                };

            this.btn_CustomerData.Click += (s, e) =>
                {
                    browserCustomerData();
                };
            this.btn_Search.Click += (s, e) =>
                {
                    searchOrders();
                };
            this.btn_Clear.Click += (s, e) =>
                {
                    clearSearchConditions();
                };
            this.cmb_SearchProject.SelectedIndexChanged += (s, e) =>
                {
                    Contract.Project project = this.cmb_SearchProject.GetValue() as Contract.Project;

                    if (project != null)
                        this.cmb_SearchSubProject.Properties.BindingData(project.SubProjectList);
                    else
                        this.cmb_SearchSubProject.Properties.BindingData(null);

                    this.cmb_SearchSubProject.SetValue(default(Contract.SubProject));
                };
        }

        protected override void LoadDatas()
        {
            bds_Customer.BindingData(_masterProxy.GetAllCustomer().ReturnValue);
            this.cmb_SearchProject.Properties.BindingData(_masterProxy.GetAllProject().ReturnValue);
            bds_Vendor.BindingData(_masterProxy.GetAllVendor().ReturnValue);

            //bds_otherBusiness.BindingData(new List<Contract.ROtherBusiness>());

            clearSearchConditions();

            SetAuthorities();
        }

        protected void SetAuthorities()
        {
            foreach (Contract.RoleAuthorizedItem roleAuthorizedItem in AppParameters.LoginUser.Role.Authorities)
            {
                switch (roleAuthorizedItem.AuthorizedItem.Name)
                {
                    case "其他经营项目":
                        bbt_Add.Enabled = roleAuthorizedItem.Allow;
                        bbt_Edit.Enabled = roleAuthorizedItem.Allow;
                        break;
                    case "高级修改":
                        bbt_Void.Enabled = roleAuthorizedItem.Allow;
                        break;
                }
            }
        }

        private void bar_Main_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            switch (e.Item.Name)
            {
                case "bbt_Add":
                    this.add();
                    break;
                case "bbt_Edit":
                    this.edit();
                    break;
                case "bbt_Void":
                    this.voidOrder();
                    break;
                case "bbt_Print":
                    this.printOrder();
                    break;
                case "bbt_Close":
                    this.Close();
                    break;
                default:
                    break;
            }
        }

        private void printOrder()
        {
            if (Order == null)
                return;

            BasicPrinterForm frm = new BasicPrinterForm();
            frm.Text = "打印订单";

            Print.Rpt_OtherBussiness report = new Print.Rpt_OtherBussiness();
            report.Order = Order;

            frm.Report = report;

            FormOpener.ShowDialog(frm);
        }

        private void voidOrder()
        {
            bool isSure = false;
            MsgBox.Question("确定将订单作废?", () => { isSure = true; }, null);
            if (!isSure)
                return;

            if (Order == null)
                return;

            Frm_Void frm = new Frm_Void(Order);
            frm.Text = "订单作废";
            if (FormOpener.ShowDialog(frm) == DialogResult.OK)
                searchOrders();
        }

        private void add()
        {
            Frm_OtherBusinessEdit frm = new Frm_OtherBusinessEdit();
            frm.Text = "增加订单";
            frm.ViewState = ViewStates.ADD;
            frm.Load += (s, e) =>
                {
                    frm.Order = new Contract.OtherBusiness();
                };
            FormOpener.ShowDialog(frm);

            if (frm.ReturnValue != null && this.bds_otherBusiness.DataSource is List<Contract.ROtherBusiness>)
            {
                this.bds_otherBusiness.Insert(0, frm.ReturnValue);
            }
        }

        private void edit()
        {
            if (Order == null)
                return;
            if (Order.Status == MsgResource.VoidStatus)
                return;

            Frm_OtherBusinessEdit frm = new Frm_OtherBusinessEdit();
            frm.Text = "修改订单资料";
            frm.ViewState = ViewStates.EDIT;
            frm.Load += (s, e) =>
            {
                frm.Order = Order;
            };
            if (FormOpener.ShowDialog(frm) == DialogResult.OK)
            {
                this.gv_Orders.BeginUpdate();
                this.gv_Orders.EndUpdate();
                Order = frm.Order;
            }
        }

        private void browserCustomerData()
        {
            if (Order == null)
                return;

            Frm_CustomerEdit frm = new Frm_CustomerEdit();
            frm.Text = "客户详细资料";
            frm.ViewState = ViewStates.BROWSER;
            frm.Load += (s, e) =>
            {
                frm.CurCust = Order.Customer;
            };
            FormOpener.ShowDialog(frm);
        }

        private void searchOrders()
        {
            List<Contract.ROtherBusiness> otherBusinessSource = new List<Contract.ROtherBusiness>();

            if (rad_SCustomer.Checked)
            {
                otherBusinessSource = _businessProxy.GetOtherBusinessByCustomer(this.cmb_SearchCustomer.GetValue() as Contract.RCustomer).ReturnValue;
            }
            else if (rad_SOrderDate.Checked)
            {
                otherBusinessSource = _businessProxy.GetOtherBusinessByOrderDate(this.dte_SearchStartDate.GetValue(AppParameters.FetureDateTime), this.dte_SearchEndDate.GetValue(AppParameters.FetureDateTime).AddDays(1)).ReturnValue;
            }
            else if (rad_SOrderRef.Checked)
            {
                otherBusinessSource = _businessProxy.GetOtherBusinessByRef(this.txt_SearchOrderRef.GetText()).ReturnValue;
            }
            else if (rad_SProject.Checked)
            {
                otherBusinessSource = _businessProxy.GetOtherBusinessByProject(this.cmb_SearchProject.GetValue() as Contract.Project, this.cmb_SearchSubProject.GetValue() as Contract.SubProject, string.Empty).ReturnValue;
            }
            else if (rad_SVendor.Checked)
            {
                otherBusinessSource = _businessProxy.GetOtherBusinessByVendor(this.cmb_SearchVendor.GetValue() as Contract.RVendor).ReturnValue;
            }
            else 
            {
                otherBusinessSource = _businessProxy.GetAllOtherBusiness().ReturnValue;
            }

            bool sourceIsNull = otherBusinessSource == null;
            bool sourceIsEmpty = !sourceIsNull && otherBusinessSource.Count == 0;

            if (sourceIsEmpty)
            {
                MsgBox.Info("没有找到符合条件的订单.");
                this.Order = null;
                this.bds_otherBusiness.BindingData(new List<Contract.OtherBusiness>());
            }
            else
            {
                foreach (var order in otherBusinessSource)
                {
                    if (order.Status == "已作废") 
                        order.CustomerStatus = "已作废";
                }

                this.bds_otherBusiness.BindingData(otherBusinessSource);
            }

            
        }

        private void clearSearchConditions()
        {
            this.rad_SCustomer.SetValue(false);
            this.rad_SOrderDate.SetValue(false);
            this.rad_SOrderRef.SetValue(false);
            this.rad_SProject.SetValue(false);
            this.rad_SVendor.SetValue(false);
            ControlExtensions.ClearValue(
                this.cmb_SearchCustomer,
                this.cmb_SearchProject,
                this.cmb_SearchSubProject,
                this.cmb_SearchVendor,
                this.dte_SearchEndDate,
                this.dte_SearchStartDate,
                this.txt_SearchOrderRef,
                this.txtAddress
                );

            searchOrders();
        }

        //selected other business
        private Contract.OtherBusiness _order;
        public Contract.OtherBusiness Order
        {
            get { return _order; }
            set
            {
                _order = value;
                onOrderChanged();
            }
        }

        private void onOrderChanged()
        {
            if (Order == null)
            {
                ControlExtensions.ClearValue(
                        txt_OrderRef,
                        txt_OrderUser,
                        dte_OrderDate,
                        txt_Customer,
                        txt_Project,
                        txt_SubProject,
                        txt_SalesMan,
                        txt_ProjectContent,
                        txt_Vendor,
                        txt_CustomerName,
                        dte_ProjectDate,
                        spe_Price,
                        spe_Qty,
                        spe_VendorDiscountOrBasePrice,
                        txt_Remark,
                        spe_PrintTotalPrice,
                        //txt_PaymentType,
                        //txt_BankAccount,
                        spe_TotalPrice,
                        spe_TotalVendorPrice,
                        spe_TotalProfit,
                        spe_Intergral,
                        txt_CreditTerm,
                        txt_SalesMan,
                        txt_ProvideTicketUser,
                        this.txt_CPerson,
                        this.txt_CPersonPhone,
                        this.txt_CPersonTel,
                        this.txtAddress,
                        this.dte_DeliveryDate
                    );

                rad_VendorDiscount.SetValue(false);
                rad_BasePrice.SetValue(false);
            }
            else
            {
                txt_OrderRef.SetText(Order.Ref);
                txt_OrderUser.SetText(Order.OrderUser);
                dte_OrderDate.SetValue(Order.OrderDate);
                txt_Customer.SetText(Order.Customer);
                txt_Project.SetText(Order.Project);
                txt_SubProject.SetText(Order.SubProject);
                txt_ProjectContent.SetText(Order.Content);
                txt_Vendor.SetText(Order.Vendor);
                txt_CustomerName.SetText(Order.CustomerName);
                dte_ProjectDate.SetValue(Order.ProjectDate);
                spe_Price.SetValue(Order.Price);
                spe_Qty.SetValue(Order.Qty);
                txt_CustomerName.SetText(Order.CustomerName);
                txt_CreditTerm.SetText(Order.CreditTerm);
                dte_DeliveryDate.SetValue(Order.DeliveryDate);

                txt_Remark.SetText(Order.Remark);
                spe_PrintTotalPrice.SetValue(Order.PrintTotalPrice);

                this.txt_CPerson.SetText(Order.ContactPerson);
                this.txt_CPersonTel.SetText(Order.联系电话);
                this.txt_CPersonPhone.SetText(Order.移动电话);
                //txt_PaymentType.SetText(Order.PaymentType);
                //txt_BankAccount.SetText(Order.BankAccount);

                spe_TotalPrice.SetValue(Order.TotalPrice);
                spe_TotalProfit.SetValue(Order.TotalProfit);
                spe_TotalVendorPrice.SetValue(Order.TotalVendorPrice);
                spe_Intergral.SetValue(Order.Intergral);

                if (Order.BasePrice.HasValue && !Order.VendorDiscount.HasValue)
                {
                    rad_BasePrice.SetValue(true);
                    spe_VendorDiscountOrBasePrice.SetValue(Order.BasePrice);
                }
                else if (!Order.BasePrice.HasValue && Order.VendorDiscount.HasValue)
                {
                    rad_VendorDiscount.SetValue(true);
                    spe_VendorDiscountOrBasePrice.SetValue(Order.VendorDiscount);
                }
                else
                {
                    rad_BasePrice.SetValue(false);
                    rad_VendorDiscount.SetValue(false);
                    spe_VendorDiscountOrBasePrice.SetValue(null);
                }

                this.txt_ProvideTicketUser.SetText(Order.ProvideTicketUser);
                this.txt_SalesMan.SetText(Order.Salesman);
                this.txtAddress.SetText(Order.Address);
            }
        }
    }
}
